//
//  MainViewController.m
//  IpadR
//
//  Created by edianzu on 2017/5/26.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "MainViewController.h"
#import "MainView.h"
#import "MainLeftView.h"
#import "ClassModel.h"
#import "ClassCell.h"
#import "ChooseProjectViewController.h"
#import "ChildDataViewController.h"
#import "ChildModel.h"
#import "LoginViewController.h"
#import "ChooseSchoolViewController.h"
@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSDictionary * allDataDictionary;//全部数据
@property(nonatomic,strong)NSMutableDictionary * uploadDic;//准备上传数据的最外层字典
@property(nonatomic,strong)NSMutableArray * uploadArr;//准备上传数据的中间层数组
@property(nonatomic,strong)NSMutableArray* classTypeARR;//班级种类数组
@property (nonatomic,strong)NSMutableArray * projectArr;//测试项目数组
@property(nonatomic,strong)NSMutableArray* rightNowClassArr;//大中小排序过后的全部班级数组
@property(nonatomic,strong)MainView * mainView;
@property(nonatomic,strong)MainLeftView * mainLeftView;
@property(nonatomic,strong)ClassModel * cModel;
@property(nonatomic,strong)ChildModel * childModel;
@property(nonatomic,assign)NSInteger lines;
@property(nonatomic,assign)NSInteger innum ;
@property (nonatomic,copy)NSString * AllStr;
@property(nonatomic,strong)NSMutableArray *AllSchoolArr;
@property(nonatomic,strong)NSMutableArray *AllChildArr;
@property(nonatomic,strong)NSIndexPath * indexp;
@end

@implementation MainViewController

-(void)viewWillAppear:(BOOL)animated{
//    [self.mainView removeFromSuperview];
//    [self.mainLeftView removeFromSuperview];
    [self reloaddata];
//    [self.mainView.myTableView reloadData];
}
-(void)getAllData{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    self.dataArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.bigClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.smallClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.mixClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.middleClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.beforeClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.otherClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.babyClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.classTypeARR = [[NSMutableArray alloc]initWithCapacity:0];
    self.rightNowClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    _titleStr = [ user objectForKey:@"MainTitle"];
    _classTag =[ user objectForKey:@"SchoolId"];
    NSLog(@"具体为 %@,%@",_titleStr,_classTag);
    //获取全部数据
    NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    self.AllSchoolArr = [[NSMutableArray alloc]init];
    //拿到所有班级的数组
    self.AllSchoolArr = dict[@"Classes"];
    //取出当前园所的所有班级
    for (NSDictionary * dic in self.AllSchoolArr) {
        self.cModel = [ClassModel modelWithDictionary:dic];
        //循环取出班级所属幼儿园ID = CLASSTAG的模型，则为当前所需班级
        if ([self.cModel.KindergartenId isEqual:_classTag]) {
            [self.dataArr addObject:self.cModel];
        }
    }
    //取出所有人childModel
    NSMutableArray * peopleArr = dict[@"Children"];
    self.AllChildArr = [NSMutableArray new];// 本园所的孩子
    for (NSDictionary * dic in peopleArr) {
        self.childModel = [ChildModel modelWithDictionary:dic];
        if ([self.childModel.KindergartenId isEqual: self.classTag]) {
            [self.AllChildArr addObject:self.childModel];
        }
    }

    
    //把本园所所有班级分类
    for (_cModel in _dataArr) {
        
        if ([self.cModel.ClassType isEqual:@0]) {
            [self.bigClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @1]) {
            [self.middleClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @2]) {
            [self.smallClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @3]) {
            [self.babyClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @4]) {
            [self.mixClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @5]) {
            [self.beforeClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @6]) {
            [self.otherClassArr addObject:self.cModel];
        }
    }
    
    //将班级分类和分类图片存为字典
    if (self.smallClassArr.count !=0) {
        
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"小班" forKey:@"ClassType"];
        [ClassDict setValue:@"smallClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_smallClassArr];
    }
    if (self.middleClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"中班" forKey:@"ClassType"];
        [ClassDict setValue:@"middleClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_middleClassArr];
    }
    if (self.bigClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"大班" forKey:@"ClassType"];
        [ClassDict setValue:@"bigClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_bigClassArr];
    }
    if (self.babyClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"托班" forKey:@"ClassType"];
        [ClassDict setValue:@"childClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_babyClassArr];
    }
    if (self.mixClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"混龄班" forKey:@"ClassType"];
        [ClassDict setValue:@"mixClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_mixClassArr];
    }
    if (self.beforeClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"学前班" forKey:@"ClassType"];
        [ClassDict setValue:@"beforeClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_beforeClassArr];
    }
    if (self.otherClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"其他" forKey:@"ClassType"];
        [ClassDict setValue:@"otherClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:_otherClassArr];
    }
    
    NSLog(@"====%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld",_bigClassArr.count,_middleClassArr.count,_smallClassArr.count,_babyClassArr.count,_mixClassArr.count,_beforeClassArr.count,_otherClassArr.count,_classTypeARR.count);
    
    //////////////////////////获取选择好的项目
    NSMutableArray * arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"testProject"];//从本地取出项目组
    self.projectArr = [[NSMutableArray alloc] init];//用来装项目组的ARR
    for (NSArray * dataarr in arr) {
        NSMutableArray * proDetailArr = [[NSMutableArray alloc] init];
        for (NSDictionary * dic in dataarr) {
            NSMutableDictionary * dictt = [NSMutableDictionary dictionaryWithDictionary:dic];
            //            [dictt setValue:@10 forKey:@"proValue"];
            [proDetailArr addObject:dictt];
            
        }
        [self.projectArr addObject:proDetailArr];
    }
    
    //获取园所已经完成的人数
    _innum = [self getTestedBabyWithModelArray:self.AllChildArr andProjectArray:self.projectArr];
    [self creatUIWithTestedNum:_innum];
    
    
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
    [super viewDidLoad];
    
       // Do any additional setup after loading the view.
    self.title=[ [NSUserDefaults standardUserDefaults] objectForKey:@"MainTitle"];
    self.view.backgroundColor =UIColorFromRGB(246, 246, 246);
    //创建返回按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 25,25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"naviLeft"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    [self getAllData];
    
}

-(void)leftBarBtnClicked{
    //    [self.navigationController popViewControllerAnimated:YES];
//    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pressOff)];
    [_backView addGestureRecognizer:tap];
    
    [window bringSubviewToFront:_mainLeftView];
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(0, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
//    _mainLeftView.frame.origin.x
}
//收起左边抽屉
-(void)pressOff{
    NSLog(@"收起");
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
}
#pragma mark 四个按钮方法
-(void)pressReload{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"isLogin"] ==nil) {
            [self loginReload];
        }
        else
        {
            
            //判断是否有数据需要上传，如果有，则不能更新
            NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
            //    NSLog(@"eee===%@",str);
            NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSMutableDictionary * readyToLoadArr = [[NSMutableDictionary alloc]init];
            readyToLoadArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            ///////////////
            NSInteger readyToLoadCount = 0;
            for (NSMutableDictionary * dic in [readyToLoadArr objectForKey:@"Children"]) {
                //        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
                if ([dic objectForKey:@"ValueChanged"] != nil) {
                    readyToLoadCount +=1;
                }
            }
            if (readyToLoadCount != 0) {
                [UIView animateWithDuration:0.5 animations:^{
                    _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
                }];
                [_backView removeFromSuperview];
                UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"检测到有未上传的测量数据，请先上传数据" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alc addAction:act];
                [self presentViewController:alc animated:YES completion:nil];
            }else{

            
            
    NSLog(@"更新数据");
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //     self.HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES];
    NSString * urls = @"/physicalTest/inputs";
    NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    NSDictionary *parama = @{@"AgencyId":[user objectForKey:@"AgencyId"]};
    [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
        NSLog(@"更新成功");
        [self showMessage:@"更新成功"];
        
        NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        for (NSMutableDictionary * dic in  [dict objectForKey:@"Children"]) {
            if ([[dic objectForKey:@"SitReach"] isEqual:@-111]) {
                [dic removeObjectForKey:@"SitReach"];
                
            }
        }
        NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        [user removeObjectForKey:@"AllData"];
        [user setObject:self.AllStr forKey:@"AllData"];
        [user synchronize];

        
        
        [_backView removeFromSuperview];
//        [self.mainView removeFromSuperview];
//        [self.mainLeftView removeFromSuperview];
//        [self getAllData];
        [self reloaddata];
       
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        
    } failure:^(NSError *error) {
        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"更新数据失败，请检查网络" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
        NSError * err = error;
        NSLog(@"更新因为这个失败了%@",err.description);
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        [_backView removeFromSuperview];
        
    }];
}
        }
    }
}
-(void)pressChange{
    NSLog(@"切换学校");
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
//    [self dismissViewControllerAnimated:YES completion:nil];
    ChooseSchoolViewController * cvc = [[ChooseSchoolViewController alloc]init];
    UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:cvc];
    navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
    navi.navigationBar.translucent = NO;
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    [self.navigationController presentViewController:navi animated:YES completion:nil];
//    [self.navigationController popViewControllerAnimated:YES];
}
-(void)pressProblem{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"isLogin"] ==nil) {
            [self loginLoadProblem];
        }else{
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
    NSLog(@"问题上传");
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    ///////////////////////////获取本班的孩子
    NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    self.allDataDictionary = [[NSDictionary alloc]init];
    self.uploadArr = [[NSMutableArray alloc]init];
    self.allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    ///////////////
    for (NSMutableDictionary * dic in [self.allDataDictionary objectForKey:@"Children"]) {
        //        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
            [self.uploadArr addObject:dic];
    }
    /////////////////////请求
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //     self.HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES];
    NSString * urls = @"/physicalTest/uploadRawText";
    NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
    
    //将数据转成JSON字符串
    NSData * data = [NSJSONSerialization dataWithJSONObject:_uploadArr options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
    NSNumber * kid =[ user objectForKey:@"SchoolId"];
    NSNumber * aid = [ user objectForKey:@"AgencyId"];
    NSLog(@"有啊%@,%@",kid,aid);
    NSDictionary *parama = @{@"AgencyId":aid,@"KindergartenId":kid,@"RawText":jsStr};
    manager.requestSerializer.timeoutInterval = 30;
    [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传大数据 success");
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
        [self showMessage:@"上传成功"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传大数据 error");
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败，请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
    }];
}
    }
}
-(void)pressQuit{
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
    [self sureToQuit];
    NSLog(@"退出登录");
}
//创建UI
-(void)creatUIWithTestedNum:(NSInteger)testedNum{
    _mainView = [[MainView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_mainView];
    //侧边栏
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _mainLeftView = [[MainLeftView alloc]initWithFrame:CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT)];
    [_mainLeftView.offBTN addTarget:self action:@selector(pressOff) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.reloadBtn addTarget:self action:@selector(pressReload) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.changeSchoolBtn addTarget:self action:@selector(pressChange) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.problemLoadBtn addTarget:self action:@selector(pressProblem) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.quitBtn addTarget:self action:@selector(pressQuit) forControlEvents:UIControlEventTouchUpInside];
    _mainLeftView.iconLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"companyName"];
    [window addSubview:_mainLeftView];
    
    
    //判断是否有班级数据
    if (self.dataArr.count == 0) {//无数据时
        _mainView.chooseProjectBtn.hidden =YES;
        UIView * line = [[UIView alloc]init];
        line.backgroundColor = UIColorFromRGB(227, 227, 227);
        [_mainView.myScrollView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(_mainView.mas_left);
            make.right.mas_equalTo(_mainView.mas_right);
            make.top.mas_equalTo(_mainView.checkClassStatusLabel.mas_bottom).with.offset(25*AutoScaleVertical);
            make.height.mas_equalTo(1);
        }];
        
        UILabel * remindLabel = [[UILabel alloc]init];
        remindLabel.text =@"该园所还未上传体测幼儿名单，请联系管理员处理此问题:029-6363-0163";
        remindLabel.font = [UIFont systemFontOfSize:19*AutoScaleHorizontal];
        remindLabel.textColor = [UIColor blackColor];
        [remindLabel setTextAlignment:NSTextAlignmentCenter];
        [_mainView.myScrollView addSubview:remindLabel];
        [remindLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(line.mas_bottom).with.offset(50*AutoScaleVertical);
            make.centerX.mas_equalTo(_mainView.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(1000, 30*AutoScaleVertical));
        }];
        
        _mainView.myScrollView.contentSize = CGSizeMake(0, 0);
        _mainView.testProcessLabel.text=@"0.00%";
        _mainView.unTestLabel.text = @"0";
        _mainView.schoolNumLabel.text =@"0";
        _mainView.classNumLabel.text= @"0";
    }else{
        //   CELL 总共多少
        _lines = 0;
        for (NSMutableArray * arr in _rightNowClassArr) {
            _lines += [self getCellHeight:arr];
        }
        
        
        //有数据时创建列表
        _mainView.myTableView = [[UITableView alloc]init];
        _mainView.myTableView.delegate =self;
        _mainView.myTableView.dataSource =self;
        //_mainView.myTableView.selection
        [_mainView.myTableView registerClass:[ClassCell class] forCellReuseIdentifier:@"ClassCell"];
        //包裹TABLIEVIEW 的边线
        _mainView.myTableView.layer.borderWidth = 1;
        _mainView.myTableView.layer.borderColor = [UIColorFromRGB(230, 230, 230) CGColor];//设置列表边框
        [_mainView.myScrollView addSubview:_mainView.myTableView];
        [_mainView.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_mainView.checkClassStatusLabel.mas_bottom).with.offset(25*AutoScaleVertical);
            make.left.mas_equalTo(_mainView.checkClassStatusLabel.mas_left);
            make.right.mas_equalTo(_mainView.chooseProjectBtn.mas_right);
            make.height.mas_equalTo(50 * self.classTypeARR.count * AutoScaleVertical + _lines* 125 * AutoScaleVertical);
        }];
        [_mainView.chooseProjectBtn addTarget:self action:@selector(pressChooser) forControlEvents:UIControlEventTouchUpInside];
        _mainView.upLoadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_mainView.upLoadBtn setTitle:@"上传" forState:UIControlStateNormal];
        _mainView.upLoadBtn.titleLabel.textColor = [UIColor whiteColor];
        _mainView.upLoadBtn.backgroundColor = UIColorFromRGB(30, 187, 171);
        _mainView.upLoadBtn.layer.cornerRadius = 10;
        [_mainView.upLoadBtn addTarget:self action:@selector(pressUpLoad) forControlEvents:UIControlEventTouchUpInside];
        [_mainView.myScrollView addSubview:_mainView.upLoadBtn];
        [_mainView.upLoadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_mainView.myTableView.mas_bottom).with.offset(40*AutoScaleVertical);
            make.centerX.mas_equalTo(_mainView.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 35*AutoScaleVertical));
        }];
        if (self.projectArr.count == 0) {
            _mainView.testProcessLabel.text =@"0.00%";
            _mainView.classNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.dataArr.count];
            _mainView.schoolNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count];
            _mainView.unTestLabel.text =@"---";
        }else{
        //获取园所已经完成的人数
        if (testedNum ==0) {
            _mainView.testProcessLabel.text =@"0.00%";
            _mainView.classNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.dataArr.count];
            _mainView.schoolNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count];
            _mainView.unTestLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count ];
        }else{
            _mainView.classNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.dataArr.count];
            _mainView.schoolNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count];
            _mainView.unTestLabel.text =[NSString stringWithFormat:@"%u", self.AllChildArr.count - testedNum];
            float manyChild = 0.00;
            for (ChildModel * model in self.AllChildArr) {
                manyChild+=1;
            }
            float process = testedNum/manyChild  * 100;
            _mainView.testProcessLabel.text =[NSString stringWithFormat:@"%.2f%%", process];
        }
        }
        _mainView.myScrollView.contentSize = CGSizeMake(0,(375+50*self.classTypeARR.count+125*_lines)*AutoScaleVertical );//整个SCVIEW 的竖向偏移距离
        
    }
}
//选择项目
-(void)pressChooser{
    NSLog(@"choose");
    ChooseProjectViewController * vc = [ChooseProjectViewController new];
    [self.navigationController pushViewController:vc animated:true];
}

//方法:每个CELL放四个VIEW，通过数据，算出具体CELL高度
-(NSInteger)getCellHeight:(NSMutableArray*)CellArr{
    
    if (CellArr.count == 0) {
        return 0;
    }else{
    
    float num = CellArr.count/4.0;
//    NSLog(@"12123  %.2f",num);
    NSInteger lines;
    if (num <= 1) {
        lines = 1;
    }else {
        if (CellArr.count % 4 ==0) {
            lines = CellArr.count /4;
        }else{
            lines = CellArr.count /4 + 1;
        }
    }
    return lines;
    }
}

//禁止TABLEVIEW 下拉顶部超过SCREEN
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"%f",_mainView.myTableView.contentOffset.y);
    if (_mainView.myTableView.contentOffset.y <= 0) {
        _mainView.myTableView.bounces = NO;
        
        NSLog(@"禁止下拉");
    }
    else
        if (_mainView.myTableView.contentOffset.y >= 0){
            _mainView.myTableView.bounces = YES;
            NSLog(@"允许上拉");
            
        }
}
#pragma mark    上传
-(void)pressUpLoad{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"isLogin"] ==nil) {
            [self pressLogin];
        }else{
        
    NSLog(@"开始上传");
    ///////////////////////////获取本班的孩子
    NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    self.allDataDictionary = [[NSDictionary alloc]init];
    self.uploadDic = [[NSMutableDictionary alloc]init];
    self.uploadArr = [[NSMutableArray alloc]init];
    self.allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    ///////////////
    for (NSMutableDictionary * dic in [self.allDataDictionary objectForKey:@"Children"]) {
//        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
        if ([dic objectForKey:@"ValueChanged"] != nil) {
            [self.uploadArr addObject:dic];
        }
    }
//    [self.uploadDic setObject:self.uploadArr forKey:@"PhyTests"];
    //将数据转成JSON字符串
    //********************************************************************************************************
      //  解析Json 用上面的方式会有很多空格和空行， 让服务器解析不了
//    NSData * data = [NSJSONSerialization dataWithJSONObject:_uploadArr options:NSJSONWritingPrettyPrinted  error:nil];

    NSData * data = [NSJSONSerialization dataWithJSONObject:_uploadArr options:0  error:nil];
    //********************************************************************************************************
    NSString * jsStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
    NSLog(@"123");
    
    if (self.uploadArr.count == 0) {
        [self showMessage:@"没有新测量的孩子数据"];
    }else{
           /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////请求
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //     self.HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
    NSString * urls = @"/physicalTest/upload";
    NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"wangguan  %@",URL);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
        NSLog(@"........|%@",jsStr);
    NSDictionary *parama = @{@"JsonStr":jsStr};
    
    manager.requestSerializer.timeoutInterval = 30;
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传 success");
        //将VALUECHANGGED 字段去掉
        for (NSMutableDictionary * dic in [self.allDataDictionary objectForKey:@"Children"]) {
            if ([dic objectForKey:@"ValueChanged"] != nil) {
                [dic removeObjectForKey:@"ValueChanged"];
            }
        }
        //转换格式
        NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
        self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user removeObjectForKey:@"AllData"];
        [user setObject:self.AllStr forKey:@"AllData"];
        [user synchronize];

        
        
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
        [self showMessage:@"上传成功"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSError * err = error;
        NSLog(@"因为这个失败了%@",err.description);
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败，请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
    }];
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    }
  }
}

#pragma mark tableviewDELEGATE

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    _headerView = [[UIView alloc]init];
    _headerView.backgroundColor = UIColorFromRGB(242, 242, 242);
    
    NSMutableDictionary * dic = _classTypeARR[section];
    
    _headerIMG = [[UIImageView alloc]init];
    _headerIMG.image = [UIImage imageNamed:[dic objectForKey:@"ClassImage"]];
    [_headerView addSubview:_headerIMG];
    [_headerIMG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_headerView.mas_left).with.offset(20*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_headerView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(35*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    _headerLabel = [[UILabel alloc]init];
    _headerLabel.textColor = [UIColor blackColor];
    _headerLabel.text = [dic objectForKey:@"ClassType"];
    [_headerView addSubview:_headerLabel];
    [_headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_headerIMG.mas_right).with.offset(15*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_headerView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    return _headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50*AutoScaleVertical;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 125*AutoScaleVertical*[self getCellHeight:_rightNowClassArr[indexPath.section]];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _classTypeARR.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ClassCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ClassCell"];
    //cell.userInteractionEnabled = NO;
    [cell relayoutCell:self.rightNowClassArr[indexPath.section] andIndexPath:indexPath andAllChildArr:self.AllChildArr andProArr:self.projectArr] ;
    
    __weak typeof(self) weak_self = self;
    cell.action = ^(ClassModel *model, NSIndexPath * indexp) {
        NSLog(@"%@",model.ClassName);
        //        NSLog(@"%ld",index.section);
        if (_projectArr.count ==0) {
            [self showMessage:@"请先选择项目"];
        }else{
            
            ChildDataViewController * cdvc = [[ChildDataViewController alloc]init];
            cdvc.KId = model.Id;
            NSString * nextTitle = [NSString stringWithFormat:@"%@%@",self.title, model.ClassName];
            cdvc.mainTitle = nextTitle;
            [self.navigationController pushViewController:cdvc animated:YES];
        }
    };
    
    return cell;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch  {
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark 查找以测试人数
//得到已经测试人数的方法
-(NSInteger)getTestedBabyWithModelArray:(NSMutableArray *)modelArr andProjectArray:(NSMutableArray*)projectArr{
    NSInteger testedNum  = 0;
    
    for (int i = 0; i<modelArr.count; i++) {
        ChildModel * model = modelArr[i];
        int a = 0;//完成项目
        int b = 0;//有多少项目
        if (model.IsAbsense) {
            a = a+1;
            b = b+1;
        }else{
            for (NSMutableArray * arr in projectArr) {
                for (NSMutableDictionary * dict in arr) {
                    
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"1"]) {
                        if (model.Height !=nil) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"2"]) {
                        if (model.Weight !=nil) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"3"]) {
                        if ((model.IsMentalShuttleRun )||(model.IsMotorShuttleRun )||(model.ShuttleRun !=nil)) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"4"]) {
                        if ((model.IsMentalSitReach )||(model.IsMotorSitReach )||(model.SitReach !=nil)) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"5"]) {
                        if ((model.IsMentalBroadJump )||(model.IsMotorBroadJump )||(model.BroadJump !=nil)) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"6"]) {
                        if ((model.IsMentalDoubleJump )||(model.IsMotorDoubleJump )||(model.DoubleJump !=nil)) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"7"]) {
                        if ((model.IsMentalThrow )||(model.IsMotorThrow )||(model.Throw !=nil)) {
                            a= a+1;
                        }
                    }
                    if ([[dict objectForKey:@"proNum"]isEqualToString:@"8"]) {
                        if ((model.IsMentalBalance )||(model.IsMotorBalance )||(model.Balance !=nil)) {
                            a= a+1;
                        }
                    }
                    b++;
                }
            }}
        if(a == b){
            testedNum +=1;
        }
    }
    return testedNum;}



#pragma mark 退出登陆相关

#pragma mark 删除组
-(void)sureToQuit{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    
    _backWhiteView = [[UIView alloc]init];
    _backWhiteView.backgroundColor = [UIColor whiteColor];
    [window addSubview:_backWhiteView];
    [_backWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_backView.mas_centerX);
        make.top.mas_equalTo(_backView.mas_top).with.offset(160*AutoScaleVertical);
        make.width.mas_equalTo(600*AutoScaleHorizontal);
        make.height.mas_equalTo(400*AutoScaleVertical);
    }];
    
    self.backLabel = [[UILabel alloc]init];
    self.backLabel.font = [UIFont systemFontOfSize:16*AutoScaleHorizontal];
    self.backLabel.text = @"提示";
    self.backLabel.textColor = [UIColor blackColor];
    [self.backLabel setTextAlignment:NSTextAlignmentCenter];
    [window addSubview:self.backLabel];
    [self.backLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backWhiteView.mas_centerX);
        make.top.mas_equalTo(self.backWhiteView.mas_top).with.offset(20*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    
    
    self.backLineView = [[UIView alloc]init];
    self.backLineView.backgroundColor =UIColorFromRGB(241, 241, 241);
    [window addSubview:self.backLineView];
    [self.backLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backWhiteView.mas_top).with.offset(50*AutoScaleVertical);
        make.left.mas_equalTo(self.backWhiteView.mas_left);
        make.width.mas_equalTo(self.backWhiteView);
        make.height.mas_equalTo(1*AutoScaleVertical);
    }];
    
    self.backLabel1 = [[UILabel alloc]init];
    self.backLabel1.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    [self.backLabel1 setTextAlignment:NSTextAlignmentCenter];
    self.backLabel1.text = @"确定退出登录吗？";
    self.backLabel1.textColor = [UIColor blackColor];
    [window addSubview:self.backLabel1];
    [self.backLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backWhiteView.mas_centerX);
        make.top.mas_equalTo(self.backLineView.mas_top).with.offset(100*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    
    
    self.backDeleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backDeleteBtn setBackgroundImage:[UIImage imageNamed:@"noBtn"] forState:UIControlStateNormal];
    [self.backDeleteBtn addTarget:self action:@selector(sureNos) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:self.backDeleteBtn];
    [self.backDeleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backWhiteView.mas_left).with.offset(150*AutoScaleHorizontal);
        make.bottom.mas_equalTo(self.backWhiteView.mas_bottom).with.offset(-100*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    self.backConfirmBtn = [[UIButton alloc]init];
    //    self.backConfirmBtn.layer.cornerRadius =10;
    [self.backConfirmBtn setBackgroundImage:[UIImage imageNamed:@"yesBtn"] forState:UIControlStateNormal];
    [self.backConfirmBtn addTarget:self action:@selector(sureYess) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:self.backConfirmBtn];
    [self.backConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.backWhiteView.mas_right).with.offset(-150*AutoScaleHorizontal);
        make.bottom.mas_equalTo(self.backWhiteView.mas_bottom).with.offset(-100*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
}
//取消
-(void)sureNos{
    
    [self.backView removeFromSuperview];
    [self.backWhiteView removeFromSuperview];
    [self.backDeleteBtn removeFromSuperview];
    [self.backConfirmBtn removeFromSuperview];
    [self.backLabel removeFromSuperview];
    [self.backLineView removeFromSuperview];
    [self.backLabel1 removeFromSuperview];
}
//确定删除
-(void)sureYess{
    [self.backView removeFromSuperview];
    [self.backWhiteView removeFromSuperview];
    [self.backDeleteBtn removeFromSuperview];
    [self.backConfirmBtn removeFromSuperview];
    [self.backLabel removeFromSuperview];
    [self.backLineView removeFromSuperview];
    [self.backLabel1 removeFromSuperview];
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    self.HUD.mode = MBProgressHUDModeIndeterminate;
        //     self.HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/authenticate/{provider}";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSString *str1 = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSString * logout =@"logout";
        NSDictionary *parama = @{@"provider":logout};
        [[HttpRequest sharedInstance] getWithURLString:str1 parameters:parama success:^(id responseObject) {
            NSLog(@"退出成功");
//            [UIView animateWithDuration:0.5 animations:^{
//                _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
//            }];
//            [_backView removeFromSuperview];
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            //                NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            //        NSData * data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            //        NSString * strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            //                        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            NSLog(@"------------------------------------------------------------------------");
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            //移除UserDefaults中存储的用户信息
            [userDefaults removeObjectForKey:@"UserName"];
            [userDefaults removeObjectForKey:@"PassWord"];
            [userDefaults removeObjectForKey:@"isLogin"];
            [userDefaults synchronize];
                          LoginViewController * login = [[LoginViewController alloc]init];
                UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:login];
                navi.navigationBar.barTintColor = [HexColor colorWithHexString:@"ef4e42"];
                navi.navigationBar.translucent = NO;
                [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
                [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
                [self.navigationController presentViewController:navi animated:YES completion:nil];

            
            
        } failure:^(NSError *error) {
            [UIView animateWithDuration:0.5 animations:^{
                _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
            }];
            [_backView removeFromSuperview];
            UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"登录失败，请检查网络" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alc addAction:act];
            [self presentViewController:alc animated:YES completion:nil];
            NSError * err = error;
            NSLog(@"退出因为这个失败了%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            
        }];
    }

}



#pragma mark  更新本地数据
-(void)reloaddata{
    //更新数据/////////////////////////////////////////////////////////////////
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    self.dataArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.bigClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.smallClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.mixClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.middleClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.beforeClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.otherClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.babyClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.classTypeARR = [[NSMutableArray alloc]initWithCapacity:0];
    self.rightNowClassArr = [[NSMutableArray alloc]initWithCapacity:0];
    NSLog(@"具体为 %@,%@",_titleStr,_classTag);
    //获取全部数据
    NSString* str1 = [user objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str1 dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    self.AllSchoolArr = [[NSMutableArray alloc]init];
    //拿到所有班级的数组
    self.AllSchoolArr = dict1[@"Classes"];
    //取出当前园所的所有班级
    for (NSDictionary * dic in self.AllSchoolArr) {
        self.cModel = [ClassModel modelWithDictionary:dic];
        //循环取出班级所属幼儿园ID = CLASSTAG的模型，则为当前所需班级
        if ([self.cModel.KindergartenId isEqual: self.classTag]) {
            [self.dataArr addObject:self.cModel];
        }
    }
    //取出所有人childModel
    NSMutableArray * peopleArr = dict1[@"Children"];
    self.AllChildArr = [NSMutableArray new];// 本园所的孩子
    for (NSDictionary * dic in peopleArr) {
        self.childModel = [ChildModel modelWithDictionary:dic];
        if ([self.childModel.KindergartenId  isEqual: self.classTag]) {
            [self.AllChildArr addObject:self.childModel];
        }
    }
    
    
    //把本园所所有班级分类
    for (_cModel in self.dataArr) {
        
        if ([self.cModel.ClassType isEqual:@0]) {
            [self.bigClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @1]) {
            [self.middleClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @2]) {
            [self.smallClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @3]) {
            [self.babyClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @4]) {
            [self.mixClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @5]) {
            [self.beforeClassArr addObject:self.cModel];
        }
        if ([self.cModel.ClassType  isEqual: @6]) {
            [self.otherClassArr addObject:self.cModel];
        }
    }
    
    //将班级分类和分类图片存为字典
    if (self.smallClassArr.count !=0) {
        
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"小班" forKey:@"ClassType"];
        [ClassDict setValue:@"smallClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.smallClassArr];
    }
    if (self.middleClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"中班" forKey:@"ClassType"];
        [ClassDict setValue:@"middleClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.middleClassArr];
    }
    if (self.bigClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"大班" forKey:@"ClassType"];
        [ClassDict setValue:@"bigClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.bigClassArr];
    }
    if (self.babyClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"托班" forKey:@"ClassType"];
        [ClassDict setValue:@"childClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.babyClassArr];
    }
    if (self.mixClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"混龄班" forKey:@"ClassType"];
        [ClassDict setValue:@"mixClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.mixClassArr];
    }
    if (self.beforeClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"学前班" forKey:@"ClassType"];
        [ClassDict setValue:@"beforeClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.beforeClassArr];
    }
    if (self.otherClassArr.count !=0) {
        NSMutableDictionary * ClassDict = [[NSMutableDictionary alloc]init];
        [ClassDict setValue:@"其他" forKey:@"ClassType"];
        [ClassDict setValue:@"otherClass" forKey:@"ClassImage"];
        [self.classTypeARR addObject:ClassDict];
        [self.rightNowClassArr addObject:self.otherClassArr];
    }
    
    NSLog(@"====%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld",_bigClassArr.count,_middleClassArr.count,_smallClassArr.count,_babyClassArr.count,_mixClassArr.count,_beforeClassArr.count,_otherClassArr.count,_classTypeARR.count);
    
    //////////////////////////获取选择好的项目
    NSMutableArray * arr = [user objectForKey:@"testProject"];//从本地取出项目组
    self.projectArr = [[NSMutableArray alloc] init];//用来装项目组的ARR
    for (NSArray * dataarr in arr) {
        NSMutableArray * proDetailArr = [[NSMutableArray alloc] init];
        for (NSDictionary * dic in dataarr) {
            NSMutableDictionary * dictt = [NSMutableDictionary dictionaryWithDictionary:dic];
            //            [dictt setValue:@10 forKey:@"proValue"];
            [proDetailArr addObject:dictt];
            
        }
        [self.projectArr addObject:proDetailArr];
    }
    
    [self.mainView.myTableView reloadData];
    
    
    
    if (self.projectArr.count == 0) {
        _mainView.testProcessLabel.text =@"0.00%";
        _mainView.classNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.dataArr.count];
        _mainView.schoolNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count];
        _mainView.unTestLabel.text =@"---";
    }else{
        _innum = [self getTestedBabyWithModelArray:_AllChildArr andProjectArray:_projectArr];
        //获取园所已经完成的人数
        if (_innum ==0) {
            _mainView.testProcessLabel.text =@"0.00%";
            _mainView.classNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.dataArr.count];
            _mainView.schoolNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count];
            _mainView.unTestLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count ];
        }else{
            _mainView.classNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.dataArr.count];
            _mainView.schoolNumLabel.text =[NSString stringWithFormat:@"%ld", (unsigned long)self.AllChildArr.count];
            _mainView.unTestLabel.text =[NSString stringWithFormat:@"%u", self.AllChildArr.count - _innum];
            float manyChild = 0.00;
            for (ChildModel * model in self.AllChildArr) {
                manyChild+=1;
            }
            float process = _innum/manyChild  * 100;
            _mainView.testProcessLabel.text =[NSString stringWithFormat:@"%.2f%%", process];
        }
    }

    
    
    
    
    
    /////////////////////////////////////////////////////////////////////////
}

#pragma mark  登陆后上传
-(void)pressLogin{
    NSLog(@"开始登陆");
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //     self.HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES];

    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * urls = @"/authenticate/credentials";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"%@,,,,%@",[user objectForKey:@"UserName"],[user objectForKey:@"PassWord"]);
        NSDictionary *parama = @{@"Username":[user objectForKey:@"UserName"],@"Password":[user objectForKey:@"PassWord"]};
        [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"登陆成功");
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSString * isLogin = @"isLogin";
            [user setObject:isLogin forKey:@"isLogin"];
            ////////////////////////////////////////////////////
            NSLog(@"开始上传");
            ///////////////////////////获取本班的孩子
            NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
            //    NSLog(@"eee===%@",str);
            NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            _allDataDictionary = [[NSDictionary alloc]init];
            _uploadDic = [[NSMutableDictionary alloc]init];
            _uploadArr = [[NSMutableArray alloc]init];
            _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            ///////////////
            for (NSMutableDictionary * dic in [_allDataDictionary objectForKey:@"Children"]) {
                //        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
                if ([dic objectForKey:@"ValueChanged"] != nil) {
                    [_uploadArr addObject:dic];
                }
            }
            [_uploadDic setObject:_uploadArr forKey:@"PhyTests"];
            //将数据转成JSON字符串
            //********************************************************************************************************
            //  解析Json 用上面的方式会有很多空格和空行， 让服务器解析不了
            //    NSData * data = [NSJSONSerialization dataWithJSONObject:_uploadArr options:NSJSONWritingPrettyPrinted  error:nil];
            NSData * data = [NSJSONSerialization dataWithJSONObject:_uploadArr options:nil  error:nil];
            //********************************************************************************************************
            NSString * jsStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
            NSLog(@"123");
            
            if (_uploadArr.count == 0) {
                [self showMessage:@"没有新测量的孩子数据"];
            }else{
                /////////////////////请求
                                NSString * urls = @"/physicalTest/upload";
                NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
                
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
                NSLog(@"........|%@",jsStr);
                NSDictionary *parama = @{@"JsonStr":jsStr};
                
                manager.requestSerializer.timeoutInterval = 30;
                
                [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    //将VALUECHANGGED 字段去掉
                    for (NSMutableDictionary * dic in [self.allDataDictionary objectForKey:@"Children"]) {
                        if ([dic objectForKey:@"ValueChanged"] != nil) {
                            [dic removeObjectForKey:@"ValueChanged"];
                        }
                    }
                    //转换格式
                    NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
                    self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
                    [user removeObjectForKey:@"AllData"];
                    [user setObject:self.AllStr forKey:@"AllData"];
                    [user synchronize];
                    NSLog(@"上传 success");
                    [self.HUD removeFromSuperview];
                    self.HUD = nil;
                    NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                    NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
                    [self showMessage:@"上传成功"];
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSError * err = error;
                    NSLog(@"因为这个失败了%@",err.description);
                    [self.HUD removeFromSuperview];
                    self.HUD = nil;
                    UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败，请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                    [alc addAction:act];
                    [self presentViewController:alc animated:YES completion:nil];
                }];
            }

            ///////////////////////////////////////////////////
        }failure:^(NSError *error) {
  NSError * err = error;
  NSLog(@"登陆因为这个失败了%@",err.description);
  [self.HUD removeFromSuperview];
  self.HUD = nil;
}];
    
}
#pragma mark  登录后更新
-(void)loginReload{
    
    //判断是否有数据需要上传，如果有，则不能更新
    NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary * readyToLoadArr = [[NSMutableDictionary alloc]init];
    readyToLoadArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    ///////////////
    NSInteger readyToLoadCount = 0;
    for (NSMutableDictionary * dic in [readyToLoadArr objectForKey:@"Children"]) {
        //        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
        if ([dic objectForKey:@"ValueChanged"] != nil) {
            readyToLoadCount +=1;
        }
    }
    if (readyToLoadCount != 0) {
        [UIView animateWithDuration:0.5 animations:^{
            _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
        }];
        [_backView removeFromSuperview];
        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"检测到有未上传的测量数据，请先上传数据" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
    }else{
    
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //     self.HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES];
        NSLog(@"开始登陆");
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        if ([user objectForKey:@"UserName"]!=nil) {
            NSString * urls = @"/authenticate/credentials";
            NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
            NSLog(@"%@,,,,%@",[user objectForKey:@"UserName"],[user objectForKey:@"PassWord"]);
            NSDictionary *parama = @{@"Username":[user objectForKey:@"UserName"],@"Password":[user objectForKey:@"PassWord"]};
            [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
                NSLog(@"登陆成功");
                NSString * isLogin = @"isLogin";
                [user setObject:isLogin forKey:@"isLogin"];
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                NSLog(@"更新数据");
                [UIView animateWithDuration:0.5 animations:^{
                    _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
                }];
                
                NSString * urls = @"/physicalTest/inputs";
                NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
                NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
                
                NSDictionary *parama = @{@"AgencyId":[user objectForKey:@"AgencyId"]};
                [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
                    NSLog(@"更新成功");
                    [self showMessage:@"更新成功"];
                    
                    NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                    NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
                    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    
                    NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
                    self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                    
                    [user removeObjectForKey:@"AllData"];
                    [user setObject:self.AllStr forKey:@"AllData"];
                    [user synchronize];
                    
                    
                    [_backView removeFromSuperview];
                    //        [self.mainView removeFromSuperview];
                    //        [self.mainLeftView removeFromSuperview];
                    //        [self getAllData];
                    [self reloaddata];
                    
                    [self.HUD removeFromSuperview];
                    self.HUD = nil;
                    
                } failure:^(NSError *error) {
                    UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"更新数据失败，请检查网络" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                    [alc addAction:act];
                    [self presentViewController:alc animated:YES completion:nil];
                    NSError * err = error;
                    NSLog(@"更新因为这个失败了%@",err.description);
                    [self.HUD removeFromSuperview];
                    self.HUD = nil;
                    [_backView removeFromSuperview];
                    
                }];

                
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            failure:^(NSError *error) {
            NSError * err = error;
                
        }];
        }
    }
}
#pragma mark  登录后上传问题
-(void)loginLoadProblem{
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //     self.HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES];
    NSLog(@"开始登陆");
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@"UserName"]!=nil) {
        NSString * urls = @"/authenticate/credentials";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"%@,,,,%@",[user objectForKey:@"UserName"],[user objectForKey:@"PassWord"]);
        NSDictionary *parama = @{@"Username":[user objectForKey:@"UserName"],@"Password":[user objectForKey:@"PassWord"]};
        [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"登陆成功");
            NSString * isLogin = @"isLogin";
            [user setObject:isLogin forKey:@"isLogin"];
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            [UIView animateWithDuration:0.5 animations:^{
                _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
            }];
            [_backView removeFromSuperview];
            NSLog(@"问题上传");
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            ///////////////////////////获取本班的孩子
            NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
            //    NSLog(@"eee===%@",str);
            NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            _allDataDictionary = [[NSDictionary alloc]init];
            _uploadArr = [[NSMutableArray alloc]init];
            _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            ///////////////
            for (NSMutableDictionary * dic in [_allDataDictionary objectForKey:@"Children"]) {
                //        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
                [_uploadArr addObject:dic];
            }
            //请求
            NSString * urls = @"/physicalTest/uploadRawText";
            NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
            
            //将数据转成JSON字符串
            NSData * data = [NSJSONSerialization dataWithJSONObject:_uploadArr options:NSJSONWritingPrettyPrinted error:nil];
            NSString * jsStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
            NSNumber * kid =[ user objectForKey:@"SchoolId"];
            NSNumber * aid = [ user objectForKey:@"AgencyId"];
            NSLog(@"有啊%@,%@",kid,aid);
            NSDictionary *parama = @{@"AgencyId":aid,@"KindergartenId":kid,@"RawText":jsStr};
            manager.requestSerializer.timeoutInterval = 30;
            [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSLog(@"上传大数据 success");
                [self.HUD removeFromSuperview];
                self.HUD = nil;
                NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
                [self showMessage:@"上传成功"];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"上传大数据 error");
                [self.HUD removeFromSuperview];
                self.HUD = nil;
                UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败，请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alc addAction:act];
                [self presentViewController:alc animated:YES completion:nil];
            }];

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
                                               failure:^(NSError *error) {
                                                   NSError * err = error;
                                                   
                                               }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
